define(
		[ 'text!pages/monitor/monitor.html', 'pages/monitor/monitormeta','pages/monitor/websocket','css!pages/monitor/monitor', 'uui', 'config/sys_const' ],
		function(html) {
			var init = function(element, params) {
				var viewCount = 4;//控制台数量				
				//var playerInstance = new Array(8);
				//仅适用于IE浏览器，并且安装有vlc插件，则返回true；
			    var isInsalledIEVLC = function(){  
			        var vlcObj = null;
			        var vlcInstalled= false; 
			        try {
			            vlcObj = new ActiveXObject("VideoLAN.VLCPlugin.2"); 
			            if( vlcObj != null ){ 
			                vlcInstalled = true 
			            }
			        } catch (e) {
			            vlcInstalled= false;
			        }        
			        return vlcInstalled;
			    };
			  
			    //仅适用于firefox浏览器，并且安装有vlc插件，则返回true；
			    var isInsalledFFVLC = function(){
			         var numPlugins=navigator.plugins.length;
			         for  (i=0;i<numPlugins;i++){ 
			              plugin=navigator.plugins[i];
			              if(plugin.name.indexOf("VideoLAN") > -1 || plugin.name.indexOf("VLC") > -1){ 
			                 return true;
			            }
			         }
			         return false;
			    }

				
				var viewModel = {
					searchURL : ctx + '/monitor/oplist',
					monitorDetailURL : ctx + '/monitor/monitorDetail',
					pollUpURL : ctx + "/monitor/pollUp",
					opData : new u.DataTable(monitorMetaDt),
					userData : new u.DataTable(userDt),
					monitorData1 : new u.DataTable(carDt),
					monitorData2 : new u.DataTable(carDt),
					monitorData3 : new u.DataTable(carDt),
					monitorData4 : new u.DataTable(carDt),
					
					//异常信息
				    exceptionsLight1: ko.observable(),
				    exceptionsLight2: ko.observable(),
				    exceptionsLight3: ko.observable(),
				    exceptionsLight4: ko.observable(),
				    
				    
					event : {
						checkBrowser : function(){
							var browser=navigator.appName;
					        var b_version=navigator.appVersion;
					        var version=parseFloat(b_version);
					        if ( browser=="Netscape"  && version>=4) {//iE11也是netscape
								if (!!window.ActiveXObject || "ActiveXObject" in window){
									if(!isInsalledIEVLC()){
										window.md = u.dialog({id:'Dialg0',content:"#dialog_installVLC",hasCloseMenu:true});										
									}
								}
								else  {
									if(!isInsalledFFVLC()){
										window.md = u.dialog({id:'Dialg0',content:"#dialog_installVLC",hasCloseMenu:true});
										var okBtn = document.body.querySelector("#okBtn_install");
										u.on(okBtn,'click', function(){
											md.close();
										});
									}
								}
											
					         }else if(browser=="Microsoft Internet Explorer" && version>=4) {//IE10以下
								if(!isInsalledIEVLC()){
									window.md = u.dialog({id:'Dialg0',content:"#dialog_installVLC",hasCloseMenu:true});
									var okBtn = document.body.querySelector("#okBtn_install");
									u.on(okBtn,'click', function(){
										md.close();
									});
								}
					            
					        }
						},
						/** 清除 datatable的数据 */
						clearDa : function(da) {
							da.removeAllRows();
							da.clear();
						},
						// 搜索哪个控制台未加载
						searchFreeConsole : function() {
							for (var i = 1; i <= viewCount; i++) {
								if ($('#monitor' + i).val() == '') {
									return i;
								}
							}
							return 0;
						},
						//焦点对应的是哪个控制台
						searchIndexConsole:function(opcode){
							for (var i = 1; i <= viewCount; i++) {
								if ($('#opcode' + i).val() == opcode) {
									return i;
								}
							}
							return 0;
						},

						// 初始化作业点列表
						searchOplist : function() {
							var userId = viewModel.userData.getValue("id");
							var jsonData = {
								user : userId
							};
							$.ajax({
										type : 'get',
										url : viewModel.searchURL,
										datatype : 'json',
										data : jsonData,
										contentType : 'application/json;charset=utf-8f',
										success : function(res) {
											if (res) {
												viewModel.event
														.clearDa(viewModel.opData);
												viewModel.opData
														.setSimpleData(res.detailMsg.data);
												
												viewModel.opData.setAllRowsUnSelect();
											} else {
												u.messageDialog({
													msg : '后台返回数据格式有误，请联系管理员',
													title : '数据错误',
													btnText : '确定'
												});
											}
										}
									});

						},
						// 根据作业点编码查询作业点实时车辆信息
						initCarDetail : function(selectData,freeIndex) {
							var jsonData = {
								opcode : selectData.opcode
							};
							$.ajax({
								type : 'get',
								url : viewModel.monitorDetailURL,
								datatype : 'json',
								data : jsonData,
								contentType : 'application/json;charset=utf-8',
								success : function(res) {
									if (res) {
										// 车辆信息
										viewModel['monitorData' + freeIndex].setSimpleData(res.detailMsg.data.carInfo);
										//初始化视频监控信息   TODO需要流媒体服务器提供rtmp流
										var rtspList=res.detailMsg.data.cameraRtspList;
										if(rtspList){
											if(rtspList.length>=2){
												if(rtspList[0])
													viewModel.event.setupPlayer(freeIndex*2-1, rtspList[0]);//视频a
												if(rtspList[1])
													viewModel.event.setupPlayer(freeIndex*2, rtspList[1]);//视频b
											}else{
												u.messageDialog({
													msg : '请检查该作业点是否正确配置摄像头设备！',
													title : 'warning',
													btnText : '确定'
												});
											}
										}
										
										
									}

								}
							});
						},
						//清除车辆信息
						clearCarDetail : function(index){
							viewModel['monitorData' + index].clear();
						},
						//以下用于check checkbox
		                afterAdd: function (element, index, data) {
		                    if (element.nodeType === 1) {
		                        u.compMgr.updateComp(element);
		                    }
		                },
		                //该作业点是选中还是取消选中
		                checkedStatus: function(index){
		                	var selectArray = viewModel.opData.selectedIndices();
		               
		                	for(var i = 0;i< selectArray.length;i++){
		                		if(index == selectArray[i]){
		                			return 'checked';
		                		}
		                	}
		                	return 'unchecked';
		                },
		                
		                //手动取消勾选
		                cancelChecked: function(index){
		                	var selectArray = viewModel.opData.selectedIndices();
		                	var newSelectArr = new Array();
		                	var j = 0;
		                	for(var i = 0;i< selectArray.length;i++){
		                		if(index != selectArray[i]){
		                			newSelectArr[j] = selectArray[i];
		                			j++;
		                		}
		                	}
		                	viewModel.opData.setRowsSelect(newSelectArr);
		                },
		                //初始化控制台数据
		                monitorDtBind: function(ri,freeIndex){
		                	// 找到空闲的控制台，初始化数据
							var freeIndex = viewModel.event.searchFreeConsole();

							if (freeIndex == 0) {
								// 将checkbox取消打勾
								viewModel.event.cancelChecked(ri);
								u.messageDialog({
									msg : '没有空闲的控制台',
									title : 'warning',
									btnText : '确定'
								});
								return;
							}
							
							if (ri != null) {
								
								var selectArray = viewModel.opData.selectedIndices();
								
								viewModel.opData.setRowsSelect(selectArray);
								
								var selectData = viewModel.opData.getSimpleData()[ri];
								// 作业点名称
								$('#opname' + freeIndex).html(selectData.opname);
								$('#monitor' + freeIndex).val('busy');
								$('#opcode' + freeIndex).val(selectData.opcode);

								// 初始化作业点车辆等信息
								viewModel.event
										.initCarDetail(selectData,freeIndex);
								// websocket与服务器建立连接，每个控制台建立一组socket连接包括以下内容
								// 考虑建立socket连接消息有四种：车辆基本信息、实时消息、车辆动画变化指令、异常消息。
								if(!viewModel.client){
									if(location.host == "localhost:8080"){
										viewModel.client=new Client(viewModel,_CONST.SERVER_URL_DEBUG);
									}else{
										viewModel.client=new Client(viewModel,_CONST.SERVER_URL);
									}
									
									
								}
								
																	
								viewModel.client.session.connect();
								viewModel.client.session.addMonitor(selectData.opcode,freeIndex-1);
								
							}
		                },
		                
		                
		                //控制台数据清除 
		                monitorDtClear:function(ri){
		                	var selectArray = viewModel.opData.selectedIndices();
							
							viewModel.opData.setRowsSelect(selectArray);
							
							var selectData = viewModel.opData.getSimpleData()[ri];
							
							var index = viewModel.event.searchIndexConsole(selectData.opcode);
							
							if(index != 0){
								// 作业点名称
								$('#opname' + index).html('未在线');
								$('#monitor' + index).val('');
								$('#opcode' + index).val('');
								
								// 初始化作业点车辆等信息
								viewModel.event.clearCarDetail(index);
							}
							//断开socket连接 ,修改console映射
							viewModel.client.session.removeMonitor(selectData.opcode,index-1);
							
							//结束视频
							viewModel.event.stopPlayer(index*2-1);//视频a
							viewModel.event.stopPlayer(index*2);//视频a
		                },
		                
						opclick : function(row,e) {
							//取rowindex和点击的位置有关，可能是checkbox可能是作业点文字
							var ri = e.target.parentNode.parentNode.parentNode.parentNode.getAttribute('rowindex');
							if(ri == null){
								ri = e.target.parentNode.parentNode.parentNode.getAttribute('rowindex');
							}
							
							if(ri != null){
								//如果取消选中，卸载数据；如果选中，加载数据
								if(viewModel.event.checkedStatus(ri) == 'unchecked'){
									viewModel.event.monitorDtClear(ri);
								}else{
									viewModel.event.monitorDtBind(ri);
								}
							}
						},
						gateclick: function(index,e){
							var opcode=$("#opcode"+index).val();
							var isBusy=$("#monitor"+index).val();
							var jsonData = {
									opcode : opcode,
									position : e
								};
							if(isBusy=="busy"){
								$.ajax({
									type : 'get',
									url : viewModel.pollUpURL,
									datatype : 'json',
									data : jsonData,
									contentType : 'application/json;charset=utf-8'
								});
							}
						},
						initPlayer : function(){
							var h = $(".vlc-box:eq(0)").height();
							var w = $(".vlc-box:eq(0)").width();
							$("iframe").each(function(){
								$(this).height(h);
								$(this).width(w);
							});
						},
						//载入视频
		                setupPlayer : function(playerIndex,stream){		                	
		                	var vlc=$("#vlc"+playerIndex);
							$(vlc).attr('src', "pages/monitor/player.html?url="+stream);
		                },
						stopPlayer : function(playerIndex){		                	
		                	var vlc=$("#vlc"+playerIndex);
							$(vlc).attr('src', "");
		                }
					}
				}

				$(element).html(html);
				var app = u.createApp({
					el : element, // el: '#content',
					model : viewModel
				});
				viewModel.event.initPlayer();
				viewModel.event.searchOplist();
				viewModel.event.checkBrowser();
				
			    //绑定弹窗事件-异常
				var monitorlight1 = document.body.querySelector("#monitor-light1");
				u.on(monitorlight1,'click', function(){
					window.md = u.dialog({id:'Dialg1',content:"#dialog_content1",hasCloseMenu:true});
				});
				var monitorlight2 = document.body.querySelector("#monitor-light2");
				u.on(monitorlight2,'click', function(){
					window.md = u.dialog({id:'Dialg2',content:"#dialog_content2",hasCloseMenu:true});
				});
				var monitorlight3 = document.body.querySelector("#monitor-light3");
				u.on(monitorlight3,'click', function(){
					window.md = u.dialog({id:'Dialg3',content:"#dialog_content3",hasCloseMenu:true});
				});
				var monitorlight4 = document.body.querySelector("#monitor-light4");
				u.on(monitorlight4,'click', function(){
					window.md = u.dialog({id:'Dialg4',content:"#dialog_content4",hasCloseMenu:true});
				});
				//获取视频播放器vlc
//				for(var i = 1;i<=playerInstance.length;i++){
//					playerInstance[i-1]=$("#vlc"+i)[0];
//				}
				var okBtn = document.body.querySelector(".u-msg-ok ");
				
				$(".u-msg-ok ").each(function(){
					u.on(this,'click', function(){
						window.md.close();
					});
				});
				
//				var vlc1=$("#vlc1");
////				var streama="rtsp://admin:admin@172.18.3.250:554/cam/realmonitor?channel=1&subtype=1";
//				setTimeout(
//						$(vlc1).attr('src',''),
//				50000);
			
			}
			return {
				'template' : html,
				init : function(element, arg) {
					init(element, arg);
				}
			}
		});
